import { Form, Input, Button, Checkbox, message } from 'antd'
import { UserOutlined, LockOutlined } from '@ant-design/icons'
import { useNavigate } from 'react-router-dom'
import { useAppStore } from '@/store/appStore'
import { usePost } from '@/hooks/useApis'
import styles from './index.module.less'

function Login() {
  const navigate = useNavigate()
  const setLogin = useAppStore((state) => state.setLogin)
  const [{ loading }, executeLogin] = usePost('/api/auth/login')
  
  const onFinish = async (values: any) => {
    // 临时模拟登录，实际应该调用后端 API
    if (values.username && values.password) {
      setLogin('mock-token', values.username, '', '1')
      message.success('登录成功')
      navigate('/')
      return
    } else {
      message.error('请输入用户名和密码')
    }
    
    // 实际的 API 调用（当后端准备好时启用）
    try {
      const { data } = await executeLogin({ data: values })
      setLogin(data.token, data.nickName, data.avatar, data.userId)
      message.success('登录成功')
      navigate('/')
    } catch (error) {
      message.error('登录失败')
    }
  }
  
  return (
    <div className={styles.loginContainer}>
      <div className={styles.loginBox}>
        <h2 className={styles.title}>AiFlowy 登录</h2>
        <Form
          name="login"
          initialValues={{ remember: true }}
          onFinish={onFinish}
        >
          <Form.Item
            name="username"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input prefix={<UserOutlined />} placeholder="用户名" />
          </Form.Item>
          <Form.Item
            name="password"
            rules={[{ required: true, message: '请输入密码' }]}
          >
            <Input.Password prefix={<LockOutlined />} placeholder="密码" />
          </Form.Item>
          <Form.Item>
            <Form.Item name="remember" valuePropName="checked" noStyle>
              <Checkbox>记住我</Checkbox>
            </Form.Item>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" loading={loading} block>
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}

export default Login